<?php

namespace WechatSDK\Components;

use WechatSDK\Lib\Tools;
use Exception;

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Lib' . DIRECTORY_SEPARATOR . 'Tools.php';

/**
 * @author guibinyu
 * 组件的公用父类
 *
 */
class Common
{
    const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';//域名
    const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com';
    const AUTH_URL = '/token?grant_type=client_credential&';//获取access_token地址
    public $errCode = 0;
    public $errMsg = "";
    public $appid;
    public $secret;
    public $token;
    public $access_token = '';

    public function __construct($appid, $secret, $token)
    {
        $this->appid = $appid;
        $this->secret = $secret;
        $this->token = $token;
    }

    public function getAccessToken()
    {
        $result = Tools::httpGet(self::API_URL_PREFIX . self::AUTH_URL . 'appid=' . $this->appid . '&secret=' . $this->secret);
        $result = $this->parsing($result);
        if ($result && isset($result['access_token'])) {
            $this->access_token = $result['access_token'];
            return $this->access_token;
        } else {
            return '';
        }
    }
    /**
     * 解析结果
     */
    public function parsing($result)
    {
        if ($result) {
            if (is_string($result)) {
                $json = json_decode($result, true);
                if (is_array($json)) {
                    if (isset($json['errcode'])) {
                        $this->errCode = $json['errcode'];
                        $this->errMsg = $json['errmsg'];
                    }
                    return $json;
                }
            }
        }
        return $result;
    }

    public function __call($name, $arguments)
    {
        exit("Component does not have [{$name}] method !");
    }
    /**
     * token无效抛出错误
     * @throws Exception
     */
    public function throwAccessTokenError()
    {
        if (!$this->access_token && !$this->getAccessToken()) {
            throw new Exception('Access_token  Error!', '40001');
        }
    }
}
